package com.hue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hue.entity.User;
import com.hue.mapper.UserMapper;
import com.hue.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hue.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CookieValue;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 姚凤桥
 * @since 2021-07-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Map<String, String> login(User user) {
        Map<String, String> map = new HashMap<>();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", user.getMobile());
        wrapper.eq("password", MD5Utils.MD5Encoding(user.getPassword()));
        User one = getOne(wrapper);
        if (one == null) {
            map.put("error", "用户名或密码错误");
            return map;
        }
        //登录成功
        String token = UUID.randomUUID().toString().replace("-","");
        map.put("token", token);
        redisTemplate.opsForValue().set("user:"+token,one,30, TimeUnit.MINUTES);
        return map;
    }

    /*
        用cookie的token来获取redis的用户数据
     */
    @Override
    public User getUserByToken(String token) {
        User user = (User) redisTemplate.opsForValue().get("user:" + token);
        return user;
    }
}
